<template>
	<view class="content">
		<view v-if="this.logined_username">
			当前登录用户：{{logined_username}}-{{logined_truename}}
			<br>
			<button type="primary" size="mini" @click="to_logout()">登出</button>
		</view>
		
		<view v-if="!logined_username">
			<input type="text" v-model="username" placeholder="账号">
		</view>
		<view v-if="!logined_username">
			<input type="password" v-model="password" placeholder="密码">
		</view>
		<view v-if="!logined_username">
			<button type="primary" size="mini" @click="to_submit()">登录</button>
		</view>
	</view>
</template>

<script>
	import config from '../../lib/config.js';
	export default {
		data() {
			return {
				username: '',
				password: '',
				logined_username: '',
				logined_truename: '',
			}
		},
		onLoad: function(){
			try{
				let member=uni.getStorageSync('member');
				console.log(member);
				if(typeof(member['userid'])!='undefined'){
					this.logined_username=member['username'];
					this.logined_truename=member['truename'];
				}
			}catch(e){
				//TODO handle the exception
			}
			
		},
		methods: {
			to_submit: function() {
				let username = this.username.trim();
				let password = this.password.trim();
				if (!username || !password) {
					uni.showToast({
						title: '账号和密码不能为空',
						duration: 2000,
						icon: 'none',
					});
					return;
				}
				uni.request({
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
					},
					url: config.api_url+'?action=login',
					data: {
						username: this.username,
						password: this.password,
						//密码123456
					},
					success: (res) => {
						let d = res.data;
						console.log(d);
						if (d.code == 0) {
							uni.showToast({
								title: '登录成功',
								duration: 1000
							});
							this.logined_username=this.username;
							try {
							    uni.setStorageSync('member', d.data);
							} catch (e) {
							    // error
							}
						} else {
							uni.showToast({
								title: d.msg,
								duration: 3000,
								icon: 'none',
							})
						}
					}
				})
			},
			to_logout: function(){
				try {
				    uni.removeStorageSync('member');
					this.logined_username='';
					this.logined_truename='';
					uni.showToast({
						title: '成功退出',
						duration: 2000,
						icon: 'none',
					})
				} catch (e) {
				    // error
					console.log(e);
				}
			}
		}
	}
</script>

<style>

</style>
